﻿//using ShardingCore.Core.EntityMetadatas;

//namespace ApplicationFrame.EntityFrameworkCore.Core
//{
//    /// <summary>
//    /// 复合分表策略（先按时间分表，再按哈希分表）
//    /// </summary>
//    /// <typeparam name="TEntity"></typeparam>
//    /// <typeparam name="TKey1">时间分表KEY：DateTime, DateTimeOffset</typeparam>
//    /// <typeparam name="TKey2">哈希分表KEY：long, int, ulong, uint</typeparam>
//    public class TimeHashShardingStrategy<TEntity, TKey1, TKey2> : IShardingStrategy<TEntity, Tuple<TKey1, TKey2>>
//        where TEntity : class, IShardingKey<Tuple<TKey1, TKey2>>
//    {
//        private readonly TimeShardingGranularity _timeGranularity;
//        private readonly int _hashTableCount;

//        public TimeHashShardingStrategy(TimeShardingGranularity timeGranularity, int hashTableCount)
//        {
//            _timeGranularity = timeGranularity;
//            _hashTableCount = hashTableCount;
//        }

//        /// <summary>
//        /// 获取复合分表键（时间 + 哈希键）
//        /// </summary>
//        public Tuple<TKey1, TKey2> GetShardingKey(TEntity entity)
//        {
//            return entity.GetShardingKey();
//        }

//        /// <summary>
//        /// 格式化表名：原始表名 + _时间后缀 + _哈希索引（如Order_202409_3）
//        /// </summary>
//        public string FormatTableName(string originalTableName, Tuple<TKey1, TKey2> shardingKey)
//        {
//            if (shardingKey.Item1 is not DateTime && shardingKey.Item1 is not DateTimeOffset)
//                throw new ArgumentException("type must be DateTime or DateTimeOffset", nameof(shardingKey));
//            // 时间后缀（如202409）
//            var timeSuffix = _timeGranularity switch
//            {
//                TimeShardingGranularity.Year => $"{originalTableName}_{shardingKey:yyyy}",
//                TimeShardingGranularity.Month => $"{originalTableName}_{shardingKey:yyyyMM}",
//                TimeShardingGranularity.Day => $"{originalTableName}_{shardingKey:yyyyMMdd}",
//                _ => throw new ArgumentOutOfRangeException()
//            };

//            // 哈希索引（如3）
//            var hashIndex = 0;
//            if (shardingKey.Item2 is long || shardingKey.Item2 is ulong || shardingKey.Item2 is int || shardingKey.Item2 is uint)
//                hashIndex = (int)(Convert.ToUInt64(shardingKey) % (ulong)_hashTableCount);
//            else
//                hashIndex = shardingKey.GetHashCode() % _hashTableCount;

//            return $"{originalTableName}_{timeSuffix}_{hashIndex}";
//        }

//        /// <summary>
//        /// 配置分表键元数据（需同时绑定时间和哈希键）
//        /// </summary>
//        public void Configure(EntityMetadataTableBuilder<TEntity> builder)
//        {
//            // 注意：复合分表需在实体中明确两个分表键的属性
//            builder.ShardingProperty(entity => entity.GetShardingKey().Item1); // 时间键
//            builder.ShardingProperty(entity => entity.GetShardingKey().Item2); // 哈希键
//        }
//    }
//}
